import ctypes
import json
import logging
import os
import re
import sys
import time
import traceback
from ctypes import wintypes
from datetime import date, datetime
from logging.handlers import TimedRotatingFileHandler
from pathlib import Path
from time import sleep
from typing import List, Optional, Union

import requests
import schedule
import urllib3
import yaml
from DrissionPage._elements.session_element import SessionElement
from DrissionPage._pages.mix_tab import MixTab
from DrissionPage._pages.web_page import WebPage
from colorlog import ColoredFormatter
import urllib3

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
page = WebPage()
## 要排除的短信id
exclude_msg_id_set = set()
interval_minutes = 0

robot_key = ''

table_map = {'平台1': '', '平台2': ''}
def get_base_path():
    if getattr(sys, 'frozen', False):  # 如果是 PyInstaller 打包后的运行
        return sys._MEIPASS  # 临时目录
    else:
        return os.path.dirname(os.path.abspath(__file__))  # 当前脚本路径


pass


def init_data():
    global robot_key
    base_path = get_base_path()
    config_path = os.path.join(base_path, "config.yml")
    with open(config_path, 'r', encoding='utf-8') as file:
        config = yaml.safe_load(file)
        robot_key = config['key']
    return robot_key

def get_desktop_path():
    # 获取 Windows 用户桌面路径（兼容 Win7/Win10/Win11 中文系统）
    SHGFP_TYPE_CURRENT = 0
    CSIDL_DESKTOP = 0  # 桌面
    buf = ctypes.create_unicode_buffer(wintypes.MAX_PATH)
    ctypes.windll.shell32.SHGetFolderPathW(None, CSIDL_DESKTOP, None, SHGFP_TYPE_CURRENT, buf)
    return buf.value


desktop_path = get_desktop_path()
parent_path = f'{desktop_path}/移动监控'

if not os.path.exists(parent_path):
    os.makedirs(parent_path)

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

# 创建文件处理器
file_handler = TimedRotatingFileHandler(
    filename=f'{parent_path}/app.log',
    when='midnight',  # 每天午夜分割
    interval=1,  # 每 1 天
    backupCount=7,  # 最多保留 7 个旧日志文件
    encoding='utf-8'
)
file_handler.suffix = "%Y-%m-%d"

file_handler.setLevel(logging.DEBUG)
# 创建控制台处理器
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
# 创建彩色格式化器
formatter = ColoredFormatter(
    "%(log_color)s%(asctime)s %(filename)s#%(name)s - [%(threadName)s] - %(levelname)s - %(message)s",
    datefmt='%Y-%m-%d %H:%M:%S',
    log_colors={
        'DEBUG': 'black',
        'INFO': 'green',
        'WARNING': 'yellow',
        'ERROR': 'red',
        'CRITICAL': 'red,bg_white',
    }
)
console_handler.setFormatter(formatter)

# 创建格式化器并添加到处理器
file_handler.setFormatter(formatter)
console_handler.setFormatter(formatter)
## 默认20秒
sleep_seconds = 20
# 将处理器添加到日志记录器
logger.addHandler(file_handler)
logger.addHandler(console_handler)


def get_base_path():
    if getattr(sys, 'frozen', False):  # 如果是 PyInstaller 打包后的运行
        return sys._MEIPASS  # 临时目录
    else:
        return os.path.dirname(os.path.abspath(__file__))  # 当前脚本路径


pass


def open_web():
    page.get('http://134.188.194.250:30088/')


pass


def sms_menu():
    """
    短信目录选择
    :return:
    """
    page.activate_tab(page.tab_id)
    page.ele('@@tag()=div@@class=logo', timeout=80).wait.has_rect(80)
    page.ele('@@tag()=div@@class=menuShowImg', timeout=2).focus().click()
    page.ele('@@tag()=div@@class=menu_show_content@@text()=工单系统', timeout=4).focus().click()
    ms = page.ele('@@tag()=span@@class=ui-link@@text()=移动监控',
                  timeout=4)
    ms.focus().click()
    page.wait(1, 2)
    page.browser.wait.new_tab()
    tab_page = page.browser.get_tab(title='湖南10000号智慧监控')
    table_map['平台1'] = tab_page.tab_id
    page.close()
    return page.browser


pass


def page1(tab_page: MixTab):
    tab_page.refresh()
    tab_page.wait.doc_loaded(timeout=8)
    big_box = tab_page.ele(
        'xpath://div[@id="ProvinceOrderCase"  and  @class="global-chart-ht"]/div[@class="global-bg"]/span[text()="省级工单情况"]')

    tab_page.listen.start(targets='interface/ydgzIndex/ydycl',
                          method='GET', res_type='XHR')
    big_box.parent().ele('xpath://span[text()="客服中心"]').click()
    req = tab_page.listen.steps(count=1, timeout=10)
    tab_page.wait.doc_loaded(timeout=5)
    data = None
    for e in req:
        data = e.response.body['data']
        break
    tab_page.listen.pause()
    tab_page.ele('xpath://span[text()="湖南移动故障10000号智慧监控"]').focus()
    tab_page.wait.doc_loaded(timeout=5)

    canvas = tab_page.ele('xpath://canvas[@data-zr-dom-id="zr_0"]')
    canvas.wait.stop_moving(timeout=5)
    tab_page.wait(3,5)
    path: Optional[Union[str, Path]] = f'{parent_path}'
    png_path = tab_page.get_screenshot(path=path, name='screenshot.jpg', full_page=True)

    ding_data = None
    for d in data:
        if d['group_name'] == '不满意回访小组':
            ding_data = d
            break

    ## 总量
    zl = ding_data['zl']
    ## 重复工单量
    is_repeat_accept = ding_data['is_repeat_accept']
    ## 逾限
    yx = ding_data['yx']
    ## 催单量
    cd = ding_data['area_id']
    ## 在岗人数
    work = ding_data['worker']
    return zl, is_repeat_accept, yx, cd, work, png_path


pass


def page2(tab_page: MixTab):
    new_new_table = None
    if table_map['平台2'] == '':

        # 打开第二个页面
        button_1 = tab_page.ele(
            'xpath://div[@id="app"]/div[@class="body1"]/div[@class="body"]/div[@class="header"]//span[contains(text(), "常用功能")]')
        button_1.parent().next().focus().click()
        ydjk = tab_page.ele(
            'xpath://ul[not(contains(@style, "display: none"))]/li/button/span[contains(text(), "移动故障调度管控")]')
        ydjk.wait.has_rect(timeout=4)

        new_new_table = ydjk.click.for_new_tab(timeout=5)
        new_new_table.browser.activate_tab(new_new_table)
        table_map['平台2'] = new_new_table.tab_id
    else:
        new_new_table = tab_page.browser.get_tab(id_or_num=table_map['平台2'])
        new_new_table.browser.activate_tab(new_new_table)

    new_new_table.refresh()
    new_new_table.listen.start(targets='interface/faultClass/allDeal',
                               method='GET', res_type='XHR')
    new_new_table.wait.doc_loaded(timeout=5)
    req = new_new_table.listen.steps(count=1, timeout=10)
    new_data = None
    for e in req:
        new_data = e.response.body['data']
        break
    new_new_table.listen.pause()
    new_new_table.wait.doc_loaded(timeout=5)
    resd = new_new_table.s_ele(
        'xpath://div[@class="dialogsZg"]/div[@class="el-dialog__wrapper" and not(contains(@style, "display: none"))]',
        timeout=5)

    if isinstance(resd, SessionElement):
        ding_div = new_new_table.ele(
            'xpath://div[@id="pane-1"]//div[@role="dialog" and @aria-label="工单详情" and @class="el-dialog" and  @aria-modal="true" ]')
        ding_div.ele('xpath://div[@class="el-dialog__footer"]//span[@class="dialog-footer"]').ele(
            '@@tag()=button@@class=el-button el-button--default').click.left(by_js=True)

    trs = new_new_table.ele(
        'xpath://div[@id="pane-1"]//div[@class="table-box"]//div[@class="el-table__footer-wrapper"]//tbody[@class="has-gutter"]/tr')
    # 在岗人数
    zgrs = trs.ele('@tag()=td', index=17).text
    # 处理人数
    clzrs = trs.ele('@tag()=td', index=15).text

    yjqx = new_data["yjqx"]
    dgj = new_data["dgj"]
    dspgd = new_data["dspgd"]
    wsh30 = new_data["wsh30"]
    yxl = new_data["yxl"]
    clsd = new_data["clsd"]
    zxyh = new_data["zxyh"]
    ztzl = new_data["ztzl"]
    clzl = new_data["clzl"]
    yydq = new_data["yydq"]
    wshl = new_data["wshl"]
    cfzl = new_data["cfzl"]
    lsdf = new_data["lsdf"]
    cdzl = new_data["cdzl"]
    hmd = new_data["hmd"]
    return ztzl, clzrs, zgrs, yjqx, hmd, zxyh, lsdf


pass


def start_work():
    init_data()
    open_web()
    browser = sms_menu()
    return browser
pass


def start(browser):
    tab_page = browser.get_tab(id_or_num=table_map['平台1'])
    browser.activate_tab(id_ind_tab=table_map['平台1'])
    content, png_path = get_info(tab_page)
    send_rbot(content, png_path)
pass

## 获取要发送的信息
def get_info(tab_page):
    zl, is_repeat_accept, yx, cd, worker, png_path = page1(tab_page)
    ztzl, clzrs, zgrs, yjqx, hmd, zxyh, lsdf = page2(tab_page)
    content = f"""
        截止{get_current_time()}故障工单‌
        当前总量：{ztzl}件
        处理进度：
        ▫ 处理中：{clzrs}件（{zgrs}人在岗处理工单）
        ▫ 越级倾向工单：{yjqx}件
        ▫ 红名单用用户：{hmd}件
        ▫ 尊享用户：{zxyh}件
        ▫ 历史低分用户：{lsdf}件
        不满意回访小组
        ▫ 总量：{zl}
        ▫ 重复工单量：{is_repeat_accept}
        ▫ 催单量：{cd}
        ▫ 逾限量：{yx}
        ▫ 在岗人数：{0 if worker is None else worker}
        """
    return content, png_path


## 发送密信机器人
def send_rbot(content, png_path):
    file_res_json = file_upload(png_path)
    file_id = file_res_json['content']['id']
    send_text_message(content)
    send_image_message(file_id)


pass


###  发送信息
def send_text_message(content):
    global robot_key
    url = "https://134.175.150.182/robot/im-external/v1/webhook/send"
    params = {
        "key": robot_key
    }

    headers = {
        "Content-Type": "application/json"
    }

    data = {
        "type": "text",
        "textMsg": {
            "content": content,
            "isMentioned": True,
            "mentionType": 1,
            "mentionedMobileList": []
        }
    }

    response = requests.post(url, params=params, headers=headers, json=data, verify=False)

    print("Status Code:", response.status_code)
    print("Response Text:", response.text)


pass


## 发送图片
def send_image_message(file_id_str):
    global robot_key
    url = "https://134.175.150.182/robot/im-external/v1/webhook/send"
    params = {
        "key": robot_key
    }

    headers = {
        "Content-Type": "application/json"
    }

    data = {
        "type": "image",
        "imageMsg": {
            "fileId": file_id_str

        }
    }

    response = requests.post(url, params=params, headers=headers, json=data, verify=False)

    print("Status Code:", response.status_code)
    print("Response Text:", response.text)


pass


## 上传图片
def file_upload(image_path):
    global robot_key
    url = "https://134.175.150.182/robot/im-external/v1/webhook/upload-attachment"
    params = {
        "key": robot_key,
        "type": "1"
    }

    files = {
        'file': ('output.png', open(image_path, 'rb'), '*/*')
    }

    response = requests.post(url, params=params, files=files, verify=False)

    # print("Status Code:", response.status_code)
    # print("Response Text:", response.text)
    return response.json()


def get_current_time():
    # 获取当前时间
    now = datetime.now()
    # 格式化为 "2025年8月24日20:38:07" 格式
    formatted_time = now.strftime("%Y年%m月%d日%H:%M:%S")
    return formatted_time


pass

if __name__ == '__main__':
    try:
        browser = start_work()
        # 启动时先运行一次
        start(browser)

        schedule.every(1).hours.do(lambda: start(browser))
        while True:
            schedule.run_pending()
            time.sleep(1)
    except Exception as e:
        print(f"发生错误: {e}")  # 输出错误信息
        traceback.print_exc()
        logger.error(e, exc_info=True)

pass
